#!/usr/bin/env python
# -*- coding:utf-8 -*-
from rest_framework import serializers
from django_redis import get_redis_connection
from redis import RedisError
import logging
logger = logging.getLogger("meiduo")

class RegisterSmsCodeSerializer(serializers.Serializer):

    text = serializers.CharField(label="图片验证码",max_length=4,min_length=4,required=True)

    image_code_id = serializers.UUIDField(label='uuid')

    def validate(self, data):
        text = data.get("text")

        image_code_id = data.get("image_code_id")
        # 建立数据库链接
        redis_conn = get_redis_connection('code')
        # 获取ｒｅｄｉｓ中的图片验证码内容
        redis_text = redis_conn.get("image_%s"%image_code_id)
        if redis_text is None:
            raise serializers.ValidationError("验证码已过期")
        # 我们已经获取到了redis中的图片验证码内容，为了减少内存的占用，可以把数据库中的内容删掉
        try:
            redis_conn.delete("image_%s"%image_code_id)
        except RedisError as e:
            logger.error(e)

        if redis_text.decode().lower() != text:
            raise serializers.ValidationError("图片验证码输入有误")

        return data
